<template>
  <div
    class="main"
    :style="{
      backgroundColor: bgColor,
      width: '100%',
    }"
    v-clipboard:copy="
      tpl.copy_type == 1 && !appointShow ? customer.contact : ''
    "
  >
    <!-- <el-amap vid="amap" style="display: none" :plugin="amapPlugin" /> -->
    <van-skeleton title :row="20" :loading="tplload">
      <div :style="mainStyles" class="body">
        <div class="content" v-html="tpl.content" />
        <div class="page-form" v-if="tpl.enable_form && tpl.form_type == 2">
          <div class="price-wrap">
            <div class="left">
              <div class="on-sale-price">
                <div class="unit">￥</div>
                <div class="onSalePrice">{{ tpl.pay_money || 9.9 }}</div>
              </div>
              <div class="left-right">
                <div class="remaining-quota">
                  单独购买￥{{ tpl.original_cost || 9.9 }}
                </div>
                <!-- <div class="originPrice">
									团购{{ tpl.pay_money || 9.9 }}元抵扣{{
										(tpl.original_cost || 0) - (tpl.pay_money || 0)
									}}元
								</div> -->
              </div>
            </div>
            <div class="right price-number" v-if="tpl.discount_money * 1 == 0">
              {{ (tpl.original_cost || 0) - (tpl.pay_money || 0) }}
            </div>
            <div class="right price-number" v-else>
              {{ tpl.discount_money }}
            </div>
          </div>
          <div class="page-form-box">
            <div class="page-form-wrap">
              <div class="tips">
                还差<span class="num">1</span>人成团，剩余
                <van-count-down
                  ref="pageCountDown"
                  :time="this.groupBuyTime"
                  format="mm 分 ss 秒"
                >
                  <template #default="timeData">
                    <span class="block">0{{ timeData.minutes }}</span>
                    <span class="colon">分</span>
                    <span class="block">{{
                      timeData.seconds > 9
                        ? timeData.seconds
                        : "0" + timeData.seconds
                    }}</span>
                    <span class="colon">秒</span>
                  </template>
                </van-count-down>
              </div>

              <div class="marquee">
                <van-swipe
                  style="height: 1rem"
                  :autoplay="4500"
                  :show-indicators="false"
                  vertical
                  loop
                  :touchable="false"
                >
                  <van-swipe-item v-for="(v, i) in marqueeGroupUsers" :key="i">
                    <div class="marquee-item">
                      <img :src="require(`@/assets/image/user/${v[0]}`)" />
                      <img :src="require(`@/assets/image/user/${v[1]}`)" />
                      <img
                        src="@/assets/image/12.png"
                        @click="openChoiceCity"
                      />
                    </div>
                  </van-swipe-item>
                </van-swipe>
              </div>
              <div class="section-title">
                <div class="separator"></div>
                <div class="title">
                  选择城市{{ tpl.form_type == 2 ? "参团" : "预约" }}
                </div>
                <div class="separator"></div>
              </div>
              <city-list
                :biz_id="tpl.biz_id"
                :tpl="tpl"
                @select="choiceCityConfirm"
              />
            </div>
          </div>
        </div>
        <div class="content2" v-html="tpl.content2" />
      </div>
      <div class="fixed-wx" v-if="tpl.enable_service" @click="openCopy">
        <badge :value="3" :max="99" type="lineargradient" bounce>
          <img src="@/assets/wechat.png" alt="wechat" />
        </badge>
      </div>
    </van-skeleton>
    <div class="foot">
      <div class="wx" v-if="tpl.enable_service">
        <div class="foot-left" @click="openCopy">
          <badge :value="3" :max="99" type="lineargradient" bounce>
            <img src="@/assets/wechat.png" alt="wechat" />
          </badge>
          <span>微信：{{ customer.contact }}</span>
        </div>
        <button
          class="btn wx-copy"
          @click="openCopy"
          v-if="tpl.modal_show || tpl.wechat_tip_show"
        >
          复制微信
        </button>
      </div>
      <template v-if="tpl.enable_form">
        <div class="form" v-if="tpl.form_type != 2">
          <div class="price">
            <em>￥</em>{{ tpl.pay_money || 9.9 }}
            <div class="original">原价{{ tpl.original_cost || 9.9 }}元</div>
          </div>
          <div class="tips">
            <p>先到先得</p>
            <span>今日仅100个名额</span>
          </div>
          <button class="btn" @click="openChoiceCity">立即预约</button>
        </div>
        <div class="group_buy" v-else>
          <div class="info">
            <div class="users">
              <img
                v-for="(v, i) in groupUsers"
                :key="i"
                :src="require(`@/assets/image/user/${v}`)"
              />
              <img src="@/assets/image/12.png" />
            </div>
            <div class="info-right">
              <div class="tips">
                <div class="tip">还差<span>1人</span>成团</div>
                <van-count-down
                  ref="countDown"
                  :time="this.groupBuyTime"
                  format="mm 分 ss 秒"
                />
              </div>
              <div class="btn" @click="openChoiceCity">去拼团</div>
            </div>
          </div>
          <div class="btns">
            <div class="btn" @click="singleBuy">
              <div class="price">￥{{ tpl.original_cost || 9.9 }}</div>
              <div class="text">单独购买</div>
            </div>
            <div class="btn create-group" @click="openChoiceCity">
              <div class="price">￥{{ tpl.pay_money || 9.9 }}</div>
              <div class="text">去拼团</div>
            </div>
          </div>
        </div>
      </template>
    </div>
    <add-wechat-modal
      ref="modalTpl"
      :auto-copy="tpl.copy_type == 1"
      :qrcode="
        [4, 5].includes(customer.contact_type * 1) ? customer.image_url : ''
      "
      :wxno="customer.contact"
      @joinwx="adBehavior('copy')"
    >
      <div class="modal-tpl">
        <div class="content" v-html="tpl.modal_tpl"></div>
      </div>
    </add-wechat-modal>
    <add-wechat-modal
      ref="wechatTipTpl"
      :auto-copy="tpl.copy_type == 1"
      :qrcode="
        [4, 5].includes(customer.contact_type * 1) ? customer.image_url : ''
      "
      :wxno="customer.contact"
      @joinwx="adBehavior('copy')"
    >
      <div class="wechat-tip-tpl">
        <div class="content" v-html="tpl.wechat_tip_tpl"></div>
      </div>
    </add-wechat-modal>
    <choice-city
      v-if="!tplload"
      ref="choiceCity"
      :biz_id="tpl.biz_id"
      :tpl="tpl"
      @confirm="choiceCityConfirm"
    />
    <appoint-form
      ref="appoint"
      v-model="appointShow"
      :order_sn="order_sn"
      :tpl="tpl"
      :customer="customer"
      @appoint="adBehavior('submit')"
    />
  </div>
</template>
<script>
import Badge from "@/components/badge";
import userList from "@/assets/users.json";
import talkList from "@/assets/talks.json";
import { randomNum, timeAgo } from "@/utils";
import { isMobile, isWechat } from "@/utils/validate";

import textRange from "@/directives/text-range";
import AddWechatModal from "@/components/add-wechat-modal";
import AppointForm from "./components/appoint-form";
import ChoiceCity from "./components/choice-city";
import CityList from "./components/city-list";
import behavior from "@/mixins/behavior";
import qs from "qs";
function getCommentList(len) {
  let now = new Date().getTime();
  let list = [];
  let usrLen = userList.length;
  let talkLen = talkList.length;
  for (let i = 0; i < len; i++) {
    now -= Math.ceil(Math.random() * 1000 * Math.ceil(Math.random() * 80));
    list.push({
      avatar: randomNum(usrLen) + ".jpeg",
      rate: 5,
      user_name: userList[randomNum(usrLen)] || "未知",
      content: talkList[randomNum(talkLen)] || "非常的赞！",
      time: timeAgo(now),
    });
  }
  return list;
}
export default {
  name: "Ads",
  mixins: [behavior],
  components: {
    Badge,
    AddWechatModal,
    AppointForm,
    ChoiceCity,
    CityList,
  },
  directives: {
    textRange,
  },
  metaInfo() {
    return {
      title: this.tpl.title,
    };
  },
  data() {
    return {
      loading: true,
      appointShow: false,
      appointment: false,
      isMobile,
      isWechat,
      query: {},
      customer: {},
      mobile_firest_template: {},
      mobile_second_template: {},
      pc_firest_template: {},
      commentList: [],
      appointmentForm: {
        name: "",
        mobile: "",
      },
      order_sn: "",
      tpl: {},
      position: {},
      groupUsers: [],
      marqueeGroupUsers: [],
      activeCitys: [],
      groupBuyTime: 10 * 60 * 1000,
      amapPlugin: [
        {
          pName: "Geolocation", //定位
          events: {
            init: (o) => {
              // o 是高德地图定位插件实例
              o.getCurrentPosition((status, result) => {
                // console.log("getCurrentPosition", { result, status });
                if (status == "complete") {
                  this.position = result.position;
                  this.loaded = true; //load
                  const { addressComponent, formattedAddress } = result;
                  if (addressComponent) {
                    console.log({ addressComponent, formattedAddress });
                  }
                  this.$nextTick(); //页面渲染好后
                }
              });
            },
          },
        },
        // {
        // 	pName: "CitySearch",
        // 	events: {
        // 		init: (o) => {
        // 			o.getLocalCity((status, result) => {
        // 				if (status === "complete" && result.info === "OK") {
        // 					// console.log("getLocalCity", { result, status });
        // 				}
        // 			});
        // 		}
        // 	}
        // }
      ],
    };
  },
  computed: {
    bgColor() {
      const { bg_color } = this.tpl;
      return bg_color || "#fff";
    },
    mainStyles() {
      let pb = 0;
      const { enable_service, enable_form, form_type } = this.tpl;
      if (enable_service) {
        pb += 1.7332;
      }
      if (enable_form) {
        pb += form_type == 1 ? 1.7332 : 2.288888;
      }
      return {
        "padding-bottom": pb + "rem",
      };
    },
    qrcode() {
      const { contact_type, image_url, wxk_image_url } = this.customer;
      if (contact_type == 4) {
        return image_url;
      }
      if (contact_type == 5) {
        return wxk_image_url;
      }
      return "";
    },
  },
  created() {
    this.init();
  },
  mounted() {
    // this.loopCommentList();
    this.loopGroupUsers();
    this.loopMarqueeGroupUsers();
    this.$once("hook:beforeDestroy", () => {
      // clearTimeout(this.timer1);
      clearTimeout(this.timer2);
      clearTimeout(this.timer3);
    });
  },
  methods: {
    init() {
      const { id, type } = this.$route.query;
      this.getTplInfo(id, type);
      this.getCus();
    },
    loopCommentList() {
      this.commentList = getCommentList(3);
      this.timer1 = setTimeout(() => {
        this.loopCommentList();
      }, 3 * 1000);
    },
    // C端 -- 客服信息 - 获取
    async getCus() {
      const { query } = this.$route;
      const data = await this.$api.getAdCustomer(query);
      this.customer = data;
      this.adVisit(data);
    },
    // C端 -- 客服 - 点击数 - 提交
    async adVisit() {
      const { contact, contact_type, user_id, type, id } = this.customer;
      if (!id) return;
      const { id: templateId } = this.tpl;
      const { query } = this.$route;
      await this.$api.adVisit({
        contact,
        contact_type,
        ad_customer_id: id,
        user_id,
        type,
        id: templateId,
        id_stage: 0,
        id_supplier: 0,
        ...query,
      });
    },
    async adBehavior(behavior) {
      const { contact, contact_type, id, user_id, type } = this.customer;
      const { id: templateId } = this.tpl;
      const { query } = this.$route;
      this.behavior(behavior);
      await this.$api.adBehavior({
        type,
        user_id,
        ad_customer_id: id,
        id: templateId,
        contact,
        contact_type,
        id_stage: 0,
        id_supplier: 0,
        actionType: behavior,
        ...query,
      });
    },
    // 虚假拼团用户
    loopGroupUsers() {
      this.groupUsers = this.randomGroupUsers();
      this.timer2 = setTimeout(() => {
        this.loopGroupUsers();
        this.$refs.pageCountDown?.reset?.();
        this.$refs.countDown?.reset?.();
      }, this.groupBuyTime);
    },
    loopMarqueeGroupUsers() {
      let list = [];
      for (let i = 0; i < 15; i++) {
        list.push(this.randomGroupUsers());
      }
      this.marqueeGroupUsers = list;
      this.timer3 = setTimeout(() => {
        this.loopMarqueeGroupUsers();
      }, 14 * 5 * 1000);
    },
    randomGroupUsers() {
      return [randomNum(60) + ".jpeg", randomNum(60) + ".jpeg"];
    },
    openCopy() {
      if (this.tpl.modal_show) {
        this.$refs.modalTpl.open();
      }
      if (this.tpl.wechat_tip_show) {
        this.$refs.wechatTipTpl.open();
      }
    },
    singleBuy() {
      const { original_cost } = this.tpl;
      this.$dialog
        .confirm({
          title: "提示",
          message: `¥${original_cost}预约已满，推荐直接参团优惠购买👇`,
          closeOnClickOverlay: true,
          confirmButtonColor: "#ff4b00",
          confirmButtonText: "去拼团",
        })
        .then(() => {
          this.openChoiceCity();
        });
    },
    // 打开选择城市预约
    async openChoiceCity() {
      // this.$refs.appoint.open();
      const { form_pay } = this.tpl;

      if (form_pay != 2) {
        this.$refs.choiceCity.open();
        return;
      }
      await this.adSubmit();
    },
    // 选择城市预约确定
    async choiceCityConfirm(v) {
      // if (!v.length) {
      // 	this.$toast("请选择城市参团");
      // 	return;
      // }
      const { form_pay } = this.tpl;
      if (form_pay != 2) {
        this.$refs.appoint.open(v);
        return;
      }
      await this.adSubmit();
    },
    async adSubmit() {
      const { query } = this.$route;
      const {
        is_payment,
        biz_id,
        id: view_id,
        form_type,
        form_pay,
        pay_money,
      } = this.tpl;

      let queryStr = qs.stringify(query) || "";

      let toast = this.$toast.loading();
      this.adBehavior("submit");
      const res = await this.$api
        .adSubmit({
          ad_return: queryStr,
          tg_id: query.id,
          tg_type: query.type,
          order_sn: this.order_sn,
          biz_id,
          view_id,
          is_payment,
          form_type,
          form_pay,
          pay_money,
          // user_id
        })
        .catch((err) => {
          toast.clear();
          this.$toast(err);
          throw err;
        });
      location.href = res.url;
    },
  },
};
</script>
<style lang="scss" scoped>
.main {
  font-size: 0.3733rem;
  min-width: 320px;
  max-width: 640px;
  overflow: auto;
  word-break: break-all;
  word-wrap: break-word;
  width: 100%;
  margin: 0 auto;
  height: auto;
  min-height: 100%;
  // user-select: none;
  ::v-deep iframe {
    width: 100%;
  }
}

.page-form {
  background: #f7f7f7;
  .price-wrap {
    display: flex;
    background: no-repeat url(~@/assets/image/10.jpg);
    background-size: cover;
    color: #fff;
    height: 1.5866rem;
    position: relative;
    .left {
      display: flex;
      align-items: center;
      flex: 1;
      .on-sale-price {
        display: flex;
        align-items: baseline;
        margin-left: 0.3111111rem;
        font-weight: bold;
        color: #ffffff;
        margin-right: 5px;
        .unit {
          font-size: 0.355555rem;
        }
        .onSalePrice {
          line-height: 1rem;
          font-size: 0.844444rem;
          margin-top: 1px;
        }
      }
      .left-right {
        margin-left: 4px;
        margin-top: 4px;
        .remaining-quota {
          display: inline-block;
          height: 0.355555rem;
          line-height: 0.355555rem;
          padding: 0 0.2rem 0 0.2222222rem;
          font-size: 0.24444444rem;
          text-align: center;
          color: #ff041e;
          background: linear-gradient(180deg, #ffffff -6.05%, #ffd879 100%);
          box-shadow: 0px 2px 4px #f00035;
          border-radius: 0.177777rem 0.177777rem 0.177777rem 0;
        }
        .originPrice {
          height: 0.44444444rem;
          line-height: 0.44444444rem;
          opacity: 0.8;
          font-size: 0.2222222rem;
          font-weight: 400;
          color: #ffffff;
        }
      }
    }

    .right {
      position: absolute;
      right: 0.33333rem;
      bottom: 0.2444444rem;
      font-weight: 600;
      font-size: 0.33333rem;
      line-height: 15px;
      color: #fff2d2;
      &::before {
        content: "￥";
        font-size: 0.3rem;
        font-weight: 600;
      }
    }
  }
  &-box {
    padding: 0.26666rem;
  }
  &-wrap {
    padding: 0.48888rem 0.22222rem;
    background: #fff;
    border-radius: 6px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .tips {
      display: flex;
      align-items: center;
      .num {
        color: #ff4b00;
      }
      .van-count-down {
        margin-left: 4px;
      }
      .colon,
      .block {
        display: inline-block;
      }
      .colon {
        padding: 0px 3px;
        color: #fe473d;
      }
      .block {
        width: 30px;
        color: #fff;
        font-size: 12px;
        padding: 0px 6px;
        border-radius: 3px;
        text-align: center;
        background-color: #fe473d;
      }
    }

    .marquee {
      margin: 0.355555rem auto;
      height: 1rem;
      &-item {
        padding: 0.1rem 0;
        img {
          height: 0.8rem;
          width: 0.8rem;
          border-radius: 50%;
          border: 1px solid #e9e9e9;
          + img {
            margin-left: 4px;
          }
        }
      }
    }
    .section-title {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      margin-bottom: 0.5rem;
      .title {
        margin: 0 0.1777777rem;
        font-size: 0.44444rem;
        font-weight: bold;
      }
      .separator {
        width: 0.888888rem;
        height: 1px;
        background: #000;
        transform: scaleY(0.5);
      }
    }
    .submit {
      margin-top: 0.5rem;
      width: 100%;
    }
  }
}
.fixed-wx {
  position: fixed;
  right: 0.33333rem;
  bottom: 25%;
}
.fixed-wx img {
  height: 1.3332rem;
  width: 1.3332rem;
}
.foot {
  position: fixed;
  width: 100%;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  button:not(.van-button) {
    color: #fff;
    background-color: #28a745;
    border: 1px solid #28a745;
    height: 1.0666rem;
    padding: 0 0.4rem;
    width: 26vw;
    border-radius: 3px;
    outline: none;
    text-transform: none;
  }
  .wx,
  .form {
    height: 1.7332rem;
    line-height: 1;
    padding: 0.1111rem 0.2666rem;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: rgba(0, 0, 0, 0.7);
  }
  .form {
    background: #fff;
    color: #000;
    .price {
      font-size: 34px;
      font-weight: bold;
      em {
        font-size: 18px;
      }
      .original {
        font-size: 12px;
        font-weight: normal;
        color: #909399;
        text-decoration: line-through;
      }
    }
    .tips {
      font-size: 12px;
      span {
        margin-top: 4px;
        display: inline-block;
        text-align: center;
        border-radius: 3px;
        color: #fff;
        background: #ff4b00;
        padding: 6px 10px;
      }
    }
    button {
      background-color: #ff4b00;
      border: 1px solid #ff4b00;
    }
  }
  .foot-left {
    color: #fff;
    height: 100%;
    display: flex;
    align-items: center;
    cursor: pointer;
    flex: 1;
    img {
      height: 1.3332rem;
      width: 1.3332rem;
      overflow: hidden;
    }
    span {
      margin-left: 0.2222rem;
      font-size: 0.4rem;
      flex: 1;
    }
  }
  // 拼团
  .group_buy {
    background: #fff;
    border-top: solid 1px #f3e7df;
    .info {
      background: #fff6ee;
      height: 1.111111rem;
      padding: 0 0.3333333rem;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .users {
        img {
          height: 0.8rem;
          width: 0.8rem;
          border-radius: 50%;
          border: 1px solid #e9e9e9;
          + img {
            margin-left: 4px;
          }
        }
      }
      &-right {
        display: flex;
        align-items: center;
        .tips {
          padding: 0 0.3333333rem;
          text-align: right;
          .tip {
            font-size: 0.288888rem;
            span {
              color: #ff4b00;
              padding: 0 3px;
            }
          }
        }
        .van-count-down {
          color: #999;
          font-size: 0.26666rem;
          line-height: 1;
          margin-top: 4px;
        }
        .btn {
          display: inline-block;
          width: 1.377777rem;
          height: 0.666666rem;
          line-height: 0.666666rem;
          background: #ff4b00;
          color: #fff;
          text-align: center;
          font-size: 0.26666rem;
          box-shadow: 0 2px 6px 0 rgb(255 75 0 / 30%);
          border-radius: 4px;
        }
      }
    }
    .btns {
      display: flex;
      padding: 5px;
      .btn {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #fff;
        font-size: 0.35555rem;
        background: #ff9b00;
        height: 1.1111111rem;
        border-radius: 4px 0 0 4px;
        &.create-group {
          background: #ff4b00;
          border-radius: 0 4px 4px 0;
        }
        .price {
          font-weight: 500;
        }
        .text {
          font-size: 0.26666rem;
        }
      }
    }
  }
}
</style>
